package com.ruoyi.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * mybatis 元数据填充
 *
 * @author admin
 */
@Slf4j
@Component
public class MyBatisMetaObjectHandler implements MetaObjectHandler {

    private void insertFill(MetaObject metaObject, String filedName, Object value) {
        Object createTimeType = getFieldValByName(filedName, metaObject);
        if (createTimeType == null) {
            setFieldValByName(filedName, value, metaObject);
        }
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        LoginUser loginUserInfo;
        try {
            //判断是否需要 填充创建人
            Object createBy = metaObject.getValue("createBy");
            if (createBy != null && !createBy.toString().isEmpty()) {
                return;
            }
            loginUserInfo = SecurityUtils.getLoginUser();
        } catch (Exception e) {
            log.error("获取登录用户信息失败", e);
            throw new RuntimeException(e);
        }
        if (loginUserInfo != null) {
            insertFill(metaObject, "createDeptId", loginUserInfo.getDeptId());
            insertFill(metaObject, "createBy", loginUserInfo.getUserId());
            insertFill(metaObject, "updateBy", loginUserInfo.getUserId());
            insertFill(metaObject, "createTime", LocalDateTime.now());
            insertFill(metaObject, "updateTime", LocalDateTime.now());
        }
    }

    @Override
    public void updateFill(MetaObject meta) {
        LoginUser loginUserInfo = null;
        try {
            loginUserInfo = SecurityUtils.getLoginUser();
            ;
        } catch (BaseException e) {
            log.error("获取登录用户信息失败", e);
        }
        if (loginUserInfo != null) {
            this.strictUpdateFill(meta, "updateBy", String.class, loginUserInfo.getUserId().toString());
            this.strictUpdateFill(meta, "updateTime", LocalDateTime.class, LocalDateTime.now());
        }
    }
}
